package org.zoomdev.zoom.rpc.server;

import org.zoomdev.zoom.aop.Invoker;
import org.zoomdev.zoom.serializer.Serializer;

final class SimpleHandler implements Handler {

    private final Object service;
    private final Invoker invoker;

    private final Serializer serializer;

    private final Serializer argumentSerializer;

    private final String signature;

    public SimpleHandler(Invoker invoker,
                         Object instance,
                         Serializer serializer,
                         Serializer argumentSerializer,
                         String signature) {
        this.invoker = invoker;
        this.service = instance;
        this.serializer = serializer;
        this.argumentSerializer = argumentSerializer;
        this.signature = signature;
    }

    @Override
    public byte[] call(byte[] bytes) throws Throwable {
        Object[] args = (Object[]) argumentSerializer.deserialize(bytes);
        Object ret = invoker.invoke(service, args);
        if (ret == null) {
            return null;
        }
        return serializer.serialize(ret);
    }

    @Override
    public String toString() {
        return signature;
    }
}
